<script setup>
import { computed, ref, watch } from 'vue'
import { VerticalAlignTopOutlined } from '@ant-design/icons-vue'
import { serverHost } from '@/request/index.js'
import { message } from 'ant-design-vue'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const emits = defineEmits(['update:modelValue', 'successDown'])
const props = defineProps({
  modelValue: { type: String, default: '' },
  // 最大上传文件数
  limit: { type: Number, default: 1 }
})

const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const fileList = ref([])
// 取消
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
// 文件上传接口地址
const action = serverHost + '/goods/order/import'
// 请求头
const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}

const maxSize = 200
const beforeUpload = (file) => {
  if (file.size > maxSize * 1024 * 1024) {
    message.warning(`请上传${maxSize}M以内的文件`)
    return false
  }
  if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    message.warning(`请导入.xlsx类型文件`)
    return false
  }
}

const change = ({ file }) => {
  // console.log(file.response)
  if (file?.response) {
    if (file?.response?.code === 200) {
      message.success(file?.response?.msg)
      emits('successDown')
    } else {
      message.warning(file?.response?.msg)
    }
  }
  if (file.size > maxSize * 1024 * 1024) {
    fileList.value.pop()
  }
}
</script>

<template>
  <a-upload
    v-model:file-list="fileList"
    name="file"
    :action="action"
    :headers="headers"
    :beforeUpload="beforeUpload"
    @change="change"
    :showUploadList="false"
  >
    <AButton type="primary">
      <VerticalAlignTopOutlined />
      导入
    </AButton>
  </a-upload>
</template>

<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>